package cn.zxy.advice;

import cn.hutool.json.JSONUtil;
import cn.zxy.exception.BizException;
import cn.zxy.model.PageEduInfo;
import cn.zxy.model.ResponseDTO;
import cn.zxy.threaLocal.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {

    //支持的方法 必须改成true才能继续往下执行
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> httpMessageConverter, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        //判断返回类型是否是包含类
        if (body instanceof ResponseDTO){
            return body;
        }
        ResponseDTO dto=ResponseDTO.success(body);


        PageEduInfo pageEduInfo= LocalPageInfoUtil.get();
        if(pageEduInfo !=null){
            Map<Object,Object> map=new HashMap<>();
            map.put("total",pageEduInfo.getTotal());  //{"total",9}
            //进行数据封装

            map.put("items",body);
            dto=ResponseDTO.success(map);
            //删除线程
            LocalPageInfoUtil.remove();
        }

        //解决返回值是string字符串类型的
        if(httpMessageConverter == StringHttpMessageConverter.class){

            //改成json字符串
            return JSONUtil.toJsonStr(dto);
        }
        return dto;
    }

    @ExceptionHandler
    public Object processException(Exception ex){
        if(ex instanceof BizException){
            BizException bizException= (BizException) ex;
            return ResponseDTO.error(bizException.getCode(),ex.getMessage());
        }
        return  ResponseDTO.error(77,ex.getMessage());
    }
}
